package br.com.californiahotel.client.viewControler.hospede;

import br.com.californiahotel.client.architecture.viewController.BasicController;
import br.com.californiahotel.client.interfaces.AsyncCallback;
import br.com.californiahotel.client.service.HospedeService;
import br.com.californiahotel.client.service.HospedeServiceAsync;
import br.com.californiahotel.client.viewControler.hospede.HospedeFormView.Field;
import br.com.californiahotel.shared.models.Hospede;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;

public class HospedeFormController extends BasicController {

	private final HospedeServiceAsync hospedeService = GWT.create(HospedeService.class);

	public interface Display extends DisplayController {
		DynamicForm getForm();
		String getId();
	}

	public HospedeFormController(Display display) {
		super(display);
	}

	@Override
	protected void bind() {
		getItem(Field.SAVE).addClickHandler(saveButtonClickEvent());
	}

	private ClickHandler saveButtonClickEvent() {
		return new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Hospede hospede = new Hospede(getItem(Field.IDENTITY).getDisplayValue());
				hospede.setCpf(getItem(Field.CPF).getDisplayValue());
				hospede.setEndereco(getItem(Field.ADDRESS).getDisplayValue());
				hospede.setNome(getItem(Field.NAME).getDisplayValue());
				hospede.setTelefone(getItem(Field.PHONE).getDisplayValue());
				if("".equals(getDisplay().getId())){
					hospedeService.save(hospede, hospedeAsyncCallback());
				}else{
					hospedeService.edit(hospede, getDisplay().getId(), hospedeAsyncCallback());
				}
			}

			private AsyncCallback<Boolean> hospedeAsyncCallback() {
				return new AsyncCallback<Boolean>() {

					@Override
					public void onSuccess(Boolean result) {
						if (result == true) {
							SC.say("Hospede salvo com sucesso");
						} else {
							SC.say("Falha");
						}
					}
				};
			}
		};
	}

	private Display getDisplay() {
		return ((Display)getDisplayController());
	}

	private FormItem getItem(Field value) {
		return getDisplay().getForm().getItem(value.getFieldName());
	}

}
